<template>
  <el-drawer
    title="KPI指标"
    size="800px"
    :visible.sync="mVisible"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :append-to-body="true"
    :wrapperClosable="false"
  >
    <el-divider></el-divider>
    <cs-drawer-container>
      <div class="kpi-box">
        <el-form ref="kpiForm" label-position="top" :model="kpiForm" label-width="80px">
          <el-form-item label="KPI">
            <el-radio-group v-model="kpiForm.target">
              <el-radio :label="item" v-for="item in kpiTargetList" :key="item">{{ item }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-table
              :data="kpiForm.filterItems"
              style="width: 100%"
            >
              <el-table-column
                prop="platform"
                label="媒体">
                <template v-slot="{row}">
                  <el-select size="mini" v-model="row.platform" placeholder="请选择">
                    <el-option
                      v-for="item in platformList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="os"
                label="操作系统">
                <template v-slot="{row}">
                  <el-select size="mini" v-model="row.os" placeholder="请选择">
                    <el-option
                      v-for="item in oslist"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="country"
                label="投放地区">
                <template v-slot="{row}">
                  <el-select filterable clearable size="mini" v-model="row.country" placeholder="请选择">
                    <el-option
                      v-for="item in nationList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="standard"
                label="达标"
                width="200">
                <template v-slot="{row}">
                  <el-select style="width: 100px" size="mini" v-model="row.standard.condition">
                    <el-option
                      v-for="item in compareList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input style="width: 180px" type="number" size="mini" v-model="row.standard.value"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="exceed"
                label="超标"
                width="200">
                <template v-slot="{row}">
                  <el-select style="width: 100px" size="mini" v-model="row.exceed.condition">
                    <el-option
                      v-for="item in compareList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input type="number" size="mini" v-model="row.exceed.value"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                width="50">
                <template v-slot="{row, column, $index}">
                  <i class="el-icon-delete" style="cursor: pointer" @click="removeFilterItems($index)"></i>
                </template>
              </el-table-column>
            </el-table>
            <el-link type="primary" @click="addFilterItems">+ 添加指标</el-link>
          </el-form-item>
        </el-form>
      </div>
      <template v-slot:bottom>
        <el-button size="mini" type="primary" @click="submitKpiTarget">保存</el-button>
        <el-button size="mini" @click="mVisible = false">取消</el-button>
      </template>
    </cs-drawer-container>
  </el-drawer>
</template>

<script>
import {getKpiConfig, submitKpiConfig} from "@/api/offer/creativeperformance";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {getSysDictList} from "@/api/system/dict";
import _ from "lodash";

export default {
  name: "KpiConfig",
  components: {
    CsDrawerContainer
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      kpiForm: {
        target: '',
        filterItems: [{
          platform: '',
          os: '',
          country: '',
          standard: {},
          exceed: {}
        }]
      },
      // kpi指标
      kpiTargetList: ['花费', '曝光', '点击', 'CTR', '安装', 'CVR', '安装成本'],
      // 操作系统
      oslist: [
        {
          label: 'Android',
          value: '1'
        }, {
          label: 'IOS',
          value: '2'
        }, {
          label: 'Website',
          value: '3'
        }
      ],
      // 对比指标
      compareList: [
        {
          label: '>=',
          value: '>='
        }, {
          label: '>',
          value: '>'
        }, {
          label: '<',
          value: '<'
        }, {
          label: '<=',
          value: '<='
        }
      ],
      nationList: [],
      platformList: [],
      mVisible: this.visible,
      orderTargetList: [
        {
          label: '花费',
          value: 'allExpend'
        },
        {
          label: '点击',
          value: 'clicks'
        },
        {
          label: '曝光',
          value: 'impressions'
        }, {
          label: 'CTR',
          value: 'ctr'
        }, {
          label: 'CVR',
          value: 'cvr'
        }, {
          label: '安装',
          value: 'install'
        }, {
          label: '安装成本',
          value: 'installCost'
        }
      ],
    }
  },
  created() {
    this.getKpiConfig()
    getSysDictList("platforms,nation").then((map) => {
      this.platformList = map['platforms'].map(item => {
        return {
          label: item.dictValue,
          value: item.dictKey
        }
      })
      this.nationList = map['nation'].map(item => {
        return {
          label: item.dictKey,
          value: item.dictKey
        }
      })
    });
  },
  watch: {
    visible(val) {
      this.mVisible = val;
    },
    mVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    // 添加指标
    addFilterItems() {
      this.kpiForm.filterItems.push(
        {
          platform: '',
          os: '',
          country: '',
          standard: {
            condition: '',
            value: ''
          },
          exceed: {
            condition: '',
            value: ''
          }
        }
      )
    },
    // 移除指标
    removeFilterItems(index) {
      this.kpiForm.filterItems.splice(index, 1)
    },
    // 提交kpi指标
    async submitKpiTarget() {
      if (this.kpiForm.filterItems.length === 0) return this.$message.warning('请完善指标')
      const obj = this.kpiForm.filterItems.find(item => {
        return item.platform === '' || item.os === '' || item.country === '' || item.standard.condition === '' || item.standard.value === ''
      })
      if (obj !== undefined) return this.$message.warning('请完善指标')
      this.mVisible = false
      // 后端框架接收null会转义此代码作为调整
      const temp = _.cloneDeep(this.kpiForm)
      temp.filterItems = temp.filterItems.map(item => {
        if (item.exceed.condition === '' || item.exceed.value === '' || JSON.stringify(item.exceed.condition) === '{}'|| item.exceed.value === -1) {
          item.exceed = null
        }
        return item
      })
      // this.$emit('update:visible', false)
      const {data: res} = await submitKpiConfig(this.kpiForm)
      if (res.code !== 200) return
      this.$message.success('保存成功')
      const target = this.getTarget(this.kpiForm.target)
      this.$emit('submit', target)
    },
    // 获取kpi数据
    async getKpiConfig() {
      const {data: res} = await getKpiConfig()
      if (res.data.id === undefined) return
      this.kpiForm.id = res.data.id
      this.kpiForm.target = res.data.target
      this.kpiForm.filterItems = res.data.filterItems
      const target = this.getTarget(this.kpiForm.target)
      this.$emit('get-target', target)
    },
    // 返回指标
    getTarget(target) {
      return this.orderTargetList.find(item => item.label === target).value
    }
  }
}
</script>

<style lang="scss" scoped>
.kpi-box {
  padding: 0 15px;

  .el-table {
    ::v-deep .cell {
      display: flex;
    }
  }
}
</style>
